const net = require('net');
const Parer = require('./Parser');
const fs = require('fs')
const server = net.createServer((socket) => {
  socket.on('data', (data) => {
   
    let parser = new Parer(); 
    let { method, url,headers,body } = parser.parse(data); 
    // console.log('method', method); 
    // console.log('url', url);
    // console.log('headers', headers);
    // console.log('body', body);

   if (url === '/') {
          let rows = [];
          rows.push(`HTTP/1.1 200 OK`);
          rows.push(`Context-type: text-plain`);
          rows.push(`Date: ${new Date().toGMTString()}`);
          rows.push(`Connection: keep-alive`);
          rows.push(`Transfer-Encoding: chunked`);
          let responseBody = `${fs.readFileSync('./static/post.html','utf8')}`;
          rows.push(`\r\n${Buffer.byteLength(responseBody).toString(16)}\r\n${responseBody}\r\n0\r\n\r\n`);
          
          let response = rows.join('\r\n');
          socket.end(response);
          return ;
   }
  //  console.log(method, url, headers)
    if (url==='/post'){
         let rows = [];
         rows.push(`HTTP/1.1 200 OK`);
         rows.push(`Context-type: text-plain`);
         rows.push(`Date: ${new Date().toGMTString()}`);
         rows.push(`Connection: keep-alive`);
         rows.push(`Transfer-Encoding: chunked`);
        //  console.log(body)
         rows.push(`\r\n${Buffer.byteLength(body).toString(16)}\r\n${body}\r\n0\r\n\r\n`);
         let response = rows.join('\r\n');
        //  console.log(response)
         socket.end(response);
    } 
   
  });
})
server.on('error', (err) => {
  console.error(err);
});

server.listen(8082, () => {
  console.log('服务器已经启动', server.address());
});